import { ICmpnt, IPageCmpnt, IBindEvent } from 'xcore/cmpnt';
import $data from 'xcode/data';
import $cmpnt from '../bind/bind.loader';




export function bindDialog(cmpnt: ICmpnt, event: IBindEvent, title?: string, child?: ICmpnt | string, showFooter: boolean = true): ICmpnt | undefined {

    //组件未绑定，需要先创建组件，然后设置为显示状态
    if (event.action_id && event.isBind === true) {
        return $data.func.getById(event.action_id) as ICmpnt
    }

    //创建dialog
    let eventId = `${cmpnt.id}_${event.event}_${event.action}_status`
    let dialogId: string = event.action_id || ""
    if (!event.action_id) {
        let dialog: IPageCmpnt = $cmpnt.designer.find("dialog").clone() as IPageCmpnt
        dialogId = dialog.id
        dialog.props.title = title ?? dialog.props.title
        dialog.props.showFooter = showFooter
        dialog.props.valueKey = eventId
        if (!dialog.props.events) {
            dialog.props.events = {}
        }
        dialog.props.events["close"] = () => {
            $data.store.page.meta.set(eventId, false)
        }

        if (child) {
            if (typeof child === "string")
                dialog.children = [$cmpnt.designer.find(child).clone()]
            else
                dialog.children = [child]
        }
        //添加到页面
        if (!$data.store.page) throw new Error("未找到页面")
        $data.store.page.children.push(dialog)
    }

    //绑定事件
    cmpnt.events[event.event] = () => {
        $data.store.page.meta.set(eventId, true)
    }

    //设置状态

    event.action_id = dialogId
    event.isBind = true
    $data.store.page.meta.set(eventId, false)
    return $data.func.getById(dialogId) as ICmpnt
}
export function removeDialog(cmpnt: ICmpnt, event: IBindEvent) {
    if (event.action_id && event.isBind === true) {
        delete event.action_id
        delete event.isBind
        cmpnt.events[event.event] = function () { }
        $data.store.page.meta.remove(`${cmpnt.id}_${event.event}_${event.action}_status`)
    }
}